﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WineStore.DAL;
using System.Data;
using System.IO;
using WineStore.Models;
using PagedList;
using PagedList.Mvc;
using System.Data.Entity;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;


namespace WineStore.Controllers
{

    public class SimController : Controller
    {
        // Show Sim
        public ViewResult ShowSim(string sortOrder, string currentFilter1, string searchString1, int? page)
        {

            ViewBag.CurrentSort = sortOrder;
            ViewBag.SortPriceParm = sortOrder == "price asc" ? "price desc" : "price asc";

            if (Request.HttpMethod == "GET")
            {
                searchString1 = currentFilter1;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter1 = searchString1;

            using (var db = new WineDbContext())
            {
                var sims = db.Sims.Include(s => s.Supplier).Include(c => c.CategorySim);

                if (!String.IsNullOrEmpty(searchString1))
                {
                    sims = sims.Where(s => s.Supplier.SupplierName.ToUpper().Contains(searchString1.ToUpper()));
                }
                switch (sortOrder)
                {
                    case "price desc":
                        sims = sims.OrderByDescending(s => s.SimPrice);
                        break;
                    case "price asc":
                        sims = sims.OrderBy(s => s.SimPrice);
                        break;
                    default:
                        sims = sims.OrderByDescending(s => s.SimId);
                        break;
                }

                int pageSize = 20;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 10;
                pro.LinkToLastPageFormat = "Last";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "First";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }

        // Show Sim Partial
        public ViewResult ShowSimPartial(string sortOrder, string currentFilter1, string searchString1, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.SortPriceParm = sortOrder == "price asc" ? "price desc" : "price asc";
            if (Request.HttpMethod == "GET")
            {
                searchString1 = currentFilter1;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter1 = searchString1;

            using (var db = new WineDbContext())
            {
                var sims = db.Sims
                               .Include(s => s.Supplier).Include(c => c.CategorySim);

                if (!String.IsNullOrEmpty(searchString1))
                {
                    sims = sims.Where(s => s.Supplier.SupplierName.ToUpper().Contains(searchString1.ToUpper()));
                }
                switch (sortOrder)
                {
                    case "price desc":
                        sims = sims.OrderByDescending(s => s.SimPrice);
                        break;
                    case "price asc":
                        sims = sims.OrderBy(s => s.SimPrice);
                        break;
                    default:
                        sims = sims.OrderByDescending(s => s.SimId);
                        break;
                }

                int pageSize = 50;
                int pageNumber = (page ?? 1);

                // Thiet lap thuoc tinh khi phan trang
                PagedListRenderOptions pro = new PagedListRenderOptions();
                pro.MaximumPageNumbersToDisplay = 10;
                pro.LinkToLastPageFormat = "Last";
                pro.DisplayLinkToLastPage = true;
                pro.LinkToFirstPageFormat = "First";
                pro.DisplayLinkToFirstPage = true;
                pro.LinkToNextPageFormat = ">>";
                pro.DisplayLinkToNextPage = true;
                pro.LinkToPreviousPageFormat = "<<";
                pro.DisplayLinkToPreviousPage = true;

                ViewBag.Pro = pro;

                return View(sims.ToPagedList(pageNumber, pageSize));
            }
        }


        // Create Sim
        [HttpGet]
        public ActionResult CreateSim()
        {
            PopulateSuppliersDropDownList();
            PopulateCategoriesDropDownList();
            return View();
        }


        // Create Sim 
        [HttpPost]
        public ActionResult CreateSim(Sim sim)
        {
            bool flag = true;
            try
            {
                // Validate in server
                if (ModelState.IsValid)
                {

                    using (var db = new WineDbContext())
                    {
                        foreach (var item in db.Sims)
                        {
                            if (item.SimNumber.Replace(" ", "").Replace(".", "") == sim.SimNumber.Replace(" ", "").Replace(".", ""))
                            {
                                flag = false;
                                break;
                            }
                        }
                        if (flag == true)
                        {
                            
                            db.Entry(sim).State = EntityState.Added;
                            db.SaveChanges();
                            return RedirectToAction("ShowSim", "Sim");

                        }
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            PopulateSuppliersDropDownList(sim.SupplierId);
            PopulateCategoriesDropDownList(sim.CategorySimId);
            return View(sim);
        }

        // Edit Sim
        [HttpGet]
        public ActionResult EditSim(int id = 0)
        {
            Sim sim = null;
            using (var db = new WineDbContext())
            {
                sim = db.Sims.Find(id);
                if (sim == null)
                {
                    return HttpNotFound();
                }
            }
            PopulateSuppliersDropDownList(sim.SupplierId);
            PopulateCategoriesDropDownList(sim.CategorySimId);
            return View(sim);
        }


        // Edit Sim 
        [HttpPost]
        public ActionResult EditSim(Sim sim)
        {
            //bool flag = true;
            try
            {
                if (ModelState.IsValid)
                {
                    using (var db = new WineDbContext())
                    {
                        //foreach (var item in db.Sims)
                        //{
                        //    if (item.SimNumber.Replace(" ", "").Replace(".", "") == sim.SimNumber.Replace(" ", "").Replace(".", ""))
                        //    {
                        //        flag = false;
                        //        break;
                        //    }
                        //}
                        //if (flag == true)
                        //{
                        db.Entry(sim).State = EntityState.Modified;
                        db.SaveChanges();
                        return RedirectToAction("ShowSim", "Sim");
                        //}
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            PopulateSuppliersDropDownList(sim.SupplierId);
            PopulateCategoriesDropDownList(sim.CategorySimId);
            return View(sim);
        }

        // Delete Sim 
        [HttpGet]
        public ActionResult DeleteSim(int id)
        {
            Sim sim = null;
            using (var db = new WineDbContext())
            {
                sim = db.Sims.Find(id);
                ViewBag.SupplierName = sim.Supplier.SupplierName;
                ViewBag.CategoryName = sim.CategorySim.CategorySimName;
                if (sim == null)
                {
                    return HttpNotFound();
                }
            }
            return View(sim);
        }

        // POST: /Sim/DeleteSim/
        [HttpPost, ActionName("DeleteSim")]
        public ActionResult DeleteConfirmed(int id)
        {
            Sim sim = null;
            try
            {
                using (var db = new WineDbContext())
                {
                    sim = db.Sims.Find(id);

                    db.Entry(sim).State = EntityState.Deleted;
                    db.SaveChanges();
                    return RedirectToAction("ShowSim", "Sim");
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes");
            }
            return View(sim);
        }

        // Autocomplete for textbox search 
        [HttpGet]
        public ActionResult Autocomplete(string term)
        {
            using (var db = new WineDbContext())
            {
                var supplierNames = from s in db.Suppliers
                                    select s.SupplierName;
                string[] items = supplierNames.ToArray();

                var filteredItems = items.Where(
                    item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                    );
                return Json(filteredItems, JsonRequestBehavior.AllowGet);
            }
        }

        // Bind Supplier len DropDownList
        private void PopulateSuppliersDropDownList(object selectedSupplier = null)
        {
            using (var db = new WineDbContext())
            {
                var suppliersQuery = from s in db.Suppliers
                                     orderby s.SupplierName
                                     select s;
                ViewBag.SupplierId = new SelectList(suppliersQuery.ToList(), "SupplierId", "SupplierName", selectedSupplier);
            }
        }

        // Bind Category len DropDownList
        private void PopulateCategoriesDropDownList(object selectedCategory = null)
        {
            using (var db = new WineDbContext())
            {
                var categoriesQuery = from c in db.CategorySims
                                      orderby c.CategorySimName
                                      select c;
                ViewBag.CategorySimId = new SelectList(categoriesQuery.ToList(), "CategorySimId", "CategorySimName", selectedCategory);
            }
        }

        // Import Excel file
        [HttpGet]
        public ViewResult ImportExcel()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ImportExcel(HttpPostedFileBase fileExcel)
        {
            if (fileExcel != null)
            {
                string path = System.IO.Path.Combine(Server.MapPath("~/Content/FileUpload"), System.IO.Path.GetFileName(fileExcel.FileName));
                fileExcel.SaveAs(path);
                //Declare variables to hold refernces to Excel objects.
                Workbook workBook;
                SharedStringTable sharedStrings;
                IEnumerable<Sheet> workSheets;
                WorksheetPart simSheet;

                //Declare helper variables.
                string simID;

                using (SpreadsheetDocument document = SpreadsheetDocument.Open(path, true))
                {
                    //References to the workbook and Shared String Table.
                    workBook = document.WorkbookPart.Workbook;
                    workSheets = workBook.Descendants<Sheet>();
                    sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

                    //Reference to Excel Worksheet with Customer data.
                    simID = workSheets.First().Id;
                    simSheet = (WorksheetPart)document.WorkbookPart.GetPartById(simID);

                    //Load customer data to business object.
                    Sim.SaveSims(simSheet.Worksheet, sharedStrings);

                    document.Close();

                    System.IO.File.Delete(path);

                    return RedirectToAction("ShowSim");
                }
            }

            return View();
        }
    }
}

